/**
 * JFunny - A funny programming language
 * Copyright (C) 2013  fanguangping
 * Any problem email me: fguangping@gmail.com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 **/
package org.jfunny.core.dfa;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jfunny.core.ds.Arg;
import org.jfunny.core.ds.Statement;
import org.jfunny.core.ds.Symbol;

/**
 * DFA（确定的有穷自动机）的状态
 * 
 * @author fanguangping
 * 
 * 
 */
public class State {
	//是否匹配成功的标志
	private boolean accept = false;
	private int id;

	public State(int id) {
		this.id = id;
	}

	//状态转换HashMap
	private Map<Statement, State> mapping = new HashMap<Statement, State>();

	/**
	 * 根据输入，从当前状态转到下一状态
	 * @param input
	 * @param map
	 * @return
	 */
	public State transit(Statement input, Map<String, List<Statement>> map) {
		if (input instanceof Symbol) {
			State result = mapping.get((Symbol) input);
			return result;
		}
		else if (input instanceof Arg) {
			for (Statement s : mapping.keySet()) {
				//找出状态转换HashMap中的Arg，并将源语句存入替换列表中
				if (s instanceof Arg) {
					String key = s.toString();
					if (map.get(key) == null) {
						map.put(key, new ArrayList<Statement>());
					}
					map.get(key).add(input);
					return mapping.get(s);
				}
			}
		}

		return null;
	}

	public void setTransition(Statement input, State next) {
		this.mapping.put(input, next);
	}

	public void setTransition(Map<Statement, State> mapping) {
		this.mapping = mapping;
	}

	public boolean isAccept() {
		return this.accept;
	}

	public void setAccept(boolean b) {
		this.accept = b;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + id;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		State other = (State) obj;
		if (id != other.id)
			return false;
		return true;
	}

	public String toString() {
		return "State [" + id + "]";
	}
}
